/*
Copyright (C) 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var PRESET_INDICES = [
  ['.DJI', strings.DOW_JONES_INDEX],
  ['.IXIC', strings.NASDAQ_INDEX],
  ['.NYA', strings.NYSE_INDEX],
  ['.INX', strings.SP_INDEX] ];

var EXCHANGE_COLUMN = 'exchange';
var TICKER_COLUMN = 'ticker';
var NAME_COLUMN = 'name';

var isIgnoreIndexClick = false;

function onOpen() {
  init();
  view.setTimeout(function() { editTicker.focus(); }, 300);
}

function init() {
  for (var i = 0; i < PRESET_INDICES.length; ++i) {
    mainDiv.children('index' + i).onchange = function(i) {
      return function() {
        onIndexClick(PRESET_INDICES[i][0]);
      };
    }(i);
    mainDiv.children('index' + i).caption = PRESET_INDICES[i][1];
  }

  // Actually consider disabling all until ready.
  var serializedIds = options.getValue(OPTIONS_IDS_KEY);
  requestData(serializedIds, processData);
}

function processData(securities) {
  for (var i = 0; i < securities.length; ++i) {
    addItem(securities[i], false);
  }

  OptionsUI.resizeControls();
  listbox.selectedIndex = 0;

  instructions.innerText = strings.TO_SEE;
  view.onok = onOk;
  mainDiv.visible = true;
}

function onOk() {
  var ids = [];

  for (var i = 0; i < listbox.children.count; ++i) {
    var item = listbox.children(i);

    var exchange = item.children(EXCHANGE_COLUMN).innerText;
    var ticker = item.children(TICKER_COLUMN).innerText;

    var id;

    if (exchange) {
      id = exchange + ':' + ticker;
    } else {
      id = ticker;
    }

    ids.push(id);
  }

  var serializedIds = Security.serializeIds(ids);

  if (serializedIds != options.getValue(OPTIONS_IDS_KEY)) {
    options.putValue(OPTIONS_IDS_KEY, serializedIds);
  }
}

function onEditKeyPress() {
  if (event.keyCode == 13) {
    event.returnValue = false;
    onAddClick();
  }
}

function onAddClick() {
  if (!editTicker.value) {
    return;
  }

  var tickers = editTicker.value.split(' ');

  for (var i = 0; i < tickers.length; ++i) {
    var ticker = tickers[i];
    if (!ticker.trim()) {
      continue;
    }
    attemptAdd(ticker);
  }

  editTicker.value = '';
}

function attemptAdd(ticker) {
  requestData(ticker, processAttemptAdd, function() {
      processAttemptAddFail(ticker);
  });
}

function processAttemptAdd(securities) {
  if (securities.length) {
    addItem(securities[0], true);
  }
}

function processAttemptAddFail(ticker) {
  var message = Util.substitutePH(strings.INVALID_TICKER,
      '[![TICKER]!]',
      ticker);
  view.alert(message);
}

function onRemoveClick() {
  if (listbox.selectedIndex < 0 || !listbox.selectedItem) {
    return;
  }

  var item = listbox.selectedItem;
  var removedTicker =
      item.children(TICKER_COLUMN).innerText;

  removeSelectedItem();
  processIndexTicker(removedTicker, false);
}

function removeSelectedItem() {
  var index = listbox.selectedIndex;
  listbox.removeElement(listbox.selectedItem);

  if (listbox.children.count > index) {
    listbox.selectedIndex = index;
  } else {
    if (listbox.children.count > 0) {
      listbox.selectedIndex = index - 1;
    }
  }

  OptionsUI.resizeControls();
}

function onMoveUpClick() {
  if (listbox.selectedIndex <= 0) {
    return;
  }
  swapItems(listbox.selectedIndex - 1, listbox.selectedIndex);
  listbox.selectedIndex -= 1;
}

function onMoveDownClick() {
  if (listbox.selectedIndex >= listbox.children.count - 1) {
    return;
  }
  swapItems(listbox.selectedIndex + 1, listbox.selectedIndex);
  listbox.selectedIndex += 1;
}

function onIndexClick(ticker) {
  if (isIgnoreIndexClick) {
    return;
  }

  if (event.srcElement.value) {
    attemptAdd(ticker);
  } else {
    for (var i = 0; i < listbox.children.count; ++i) {
      var item = listbox.children(i);
      if (ticker == item.children(TICKER_COLUMN).innerText) {
        listbox.selectedItem = item;
        removeSelectedItem();
        return;
      }
    }
  }
}

function swapItems(indexFirst, indexSecond) {
  var firstItem = listbox.children(indexFirst);
  var secondItem = listbox.children(indexSecond);

  var savedExchange = firstItem.children(EXCHANGE_COLUMN).innerText;
  var savedTicker = firstItem.children(TICKER_COLUMN).innerText;
  var savedName = firstItem.children(NAME_COLUMN).innerText;

  firstItem.children(EXCHANGE_COLUMN).innerText =
      secondItem.children(EXCHANGE_COLUMN).innerText;
  firstItem.children(TICKER_COLUMN).innerText =
      secondItem.children(TICKER_COLUMN).innerText;
  firstItem.children(NAME_COLUMN).innerText =
      secondItem.children(NAME_COLUMN).innerText;

  secondItem.children(EXCHANGE_COLUMN).innerText = savedExchange;
  secondItem.children(TICKER_COLUMN).innerText = savedTicker;
  secondItem.children(NAME_COLUMN).innerText = savedName;
}

function addItem(security, isFront) {
  if (findItemIndex(security) >= 0) {
    var message = Util.substitutePH(strings.ALREADY_IN,
        '[![TICKER]!]',
        security.ticker);
    view.alert(message);
    return;
  }

  OptionsUI.buildItem(security, isFront);
  listbox.selectedIndex = 0;
  OptionsUI.resizeControls();
  processIndexTicker(security.ticker, true);
}

function findItemIndex(security) {
  var index = -1;

  for (var i = 0; i < listbox.children.count; ++i) {
    var item = listbox.children(i);
    if (security.ticker == item.children(TICKER_COLUMN).innerText) {
      if (security.isIndex() ||
          security.exchange == item.children(EXCHANGE_COLUMN).innerText) {
        index = i;
        break;
      }
    }
  }

  return index;
}

function processIndexTicker(ticker, value) {
  for (var i = 0; i < PRESET_INDICES.length; ++i) {
    if (PRESET_INDICES[i][0] == ticker) {
      var checkbox = mainDiv.children('index' + i);
      isIgnoreIndexClick = true;
      checkbox.value = value;
      isIgnoreIndexClick = false;
      return;
    }
  }
}

var BUTTON_NORMAL_COLOR = '#5592BB';
var BUTTON_OVER_COLOR = '#FFFFFF';

function onButtonMouseOver() {
  event.srcElement.color = BUTTON_OVER_COLOR;
}

function onButtonMouseOut() {
  event.srcElement.color = BUTTON_NORMAL_COLOR;
}
